<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class User extends Admin_Controller
{
	public function __construct()
	{
		parent::__construct();

		$this->load->model('user_model');
		$this->load->model('user_profile_model');
		$this->load->model('user_temp_model');
		$this->load->model('role_model');
		$this->load->model('permission_model');

		$this->template->set_breadcrumb('Người dùng', 'backend/user');
	}

	public function index()
	{
		//$this->auth->check_uri_permissions(true, 'backend/login');
		$this->template->title('SiteName', 'Người dùng');
		$this->template->build('backend/user/user', $this->data);
	}

	public function load($order_by = 'users.id', $order_dir = 'desc', $page = 1)
	{
		$pager_config['base_url'] = base_path() . "backend/user/load/{$order_by}/{$order_dir}/";
		$pager_config['uri_segment'] = 6;
		$pager_config['num_links'] = 3;
		$pager_config['total_rows'] = $this->user_model->count(array('users.role_id <>' => 999));
		$pager_config['per_page'] = 20;

		$limit = $pager_config['per_page'];
		$offset = $page ? (($page - 1) * $limit) : 0;
		$users = $this->user_model->find_all(array('users.role_id <>' => 999), "{$order_by} {$order_dir}", $limit, $offset)->result();
		$data['sql'] = $offset;

		$data['rows'] = "";
		foreach ($users as $row)
		{
			$data['rows'].= "<tr><td><input type=\"checkbox\" name=\"items[]\" value=\"{$row->id}\" /></td>";
			$data['rows'].= "<td>" . $row->username . "</td>";
			$data['rows'].= "<td>" . mailto($row->email, $row->email) . "</td>";
			$data['rows'].= "<td>" . $row->role_name . "</td>";
			$data['rows'].= "<td>" . $row->created . "</td>";
			$data['rows'].= "<td align=\"center\">" . $row->banned . "</td>";
			$data['rows'].= "<td align=\"center\"><div><a href=\"". base_path() . "backend/user/update/{$row->id}\" class=\"edit\">Edit</a></div></td></tr>";
		}

		$data['from_record'] 	= $pager_config['total_rows'] == 0 ? 0 : $offset + 1;
		$data['to_record'] 	= $offset + $limit > $pager_config['total_rows'] ? $pager_config['total_rows'] : $offset + $limit;
		$data['total_record'] = $pager_config['total_rows'];

		$this->pagination->initialize($pager_config);
		$data['pagination'] = $this->pagination->create_links();
		$data['message'] = 'OK';

		echo json_encode($data);
	}

	public function create()
	{
		$this->data['message'] = '';

		$validator = $this->form_validation;
		$validator->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[3]|max_length[32]|callback_check_username|alpha_dash');
		$validator->set_rules('password', 'Password', 'trim|required|xss_clean');
		$validator->set_rules('role_id', 'Group', 'trim|xss_clean|integer');
		$validator->set_rules('email', 'Email', 'trim|xss_clean|email|callback_check_email');

		$validator->set_rules('profile_name', 'Name', 'trim|xss_clean');
		$validator->set_rules('profile_yahoo', 'Yahoo Messeger', 'trim|xss_clean');
		$validator->set_rules('profile_country', 'Country', 'trim|xss_clean');
		$validator->set_rules('profile_website', 'Website', 'trim|xss_clean');

		if($validator->run())
		{
			$created = date('Y-m-d H:i:s');
			$data['username'] = $validator->set_value('username');
			$data['password'] = crypt($this->auth->_encode($validator->set_value('password')));
			$data['role_id'] = $validator->set_value('role_id');
			$data['email'] = $validator->set_value('email');
			$data['created'] = $created;

			$user_id = $this->user_model->insert($data);
			if($user_id)
			{
				$profile['user_id'] = $user_id;
				$profile['name'] = $validator->set_value('name');
				$profile['yahoo'] = $validator->set_value('yahoo');
				$profile['country'] = $validator->set_value('country');
				$profile['website'] = $validator->set_value('website');
				$profile['created'] = $created;
					
				$profile_id = $this->user_profile_model->insert($profile);
			}

			if($user_id && $profile_id)
			{
				$this->data['message'] = 'Insert success';
			}
			else
			{
				$this->data['message'] = 'Insert failed';
			}
		} 
		else
		{
			$this->data['message'] = validation_errors('<span>', '</span>');
		} 
			
		$this->data['roles'] = $this->role_model->get_all()->result();

		$this->template->title('SiteName', 'Người dùng', 'Thêm mới');
		$this->template->build('backend/user/create', $this->data);
	}

	public function update($user_id = NULL)
	{
		if($user_id)
		{
			$this->data['message'] = '';

			$validator = $this->form_validation;
			$validator->set_rules('password', 'Password', 'trim|xss_clean');
			$validator->set_rules('role_id', 'Group', 'trim|xss_clean|integer');
			$validator->set_rules('email', 'Email', 'trim|xss_clean|email|callback_check_email2');

			$validator->set_rules('profile_name', 'Name', 'trim|xss_clean');
			$validator->set_rules('profile_yahoo', 'Yahoo Messeger', 'trim|xss_clean');
			$validator->set_rules('profile_country', 'Country', 'trim|xss_clean');
			$validator->set_rules('profile_website', 'Website', 'trim|xss_clean');

			if($validator->run())
			{
				if($validator->set_value('password'))
				{
					$data['password'] = crypt($this->auth->_encode($validator->set_value('password')));
				}
				$data['role_id'] = $validator->set_value('role_id');
				$data['email'] = $validator->set_value('email');
				$this->user_model->update(array('id' => $user_id), $data);

				$profile['name'] = $validator->set_value('profile_name');
				$profile['yahoo'] = $validator->set_value('profile_yahoo');
				$profile['country'] = $validator->set_value('profile_country');
				$profile['website'] = $validator->set_value('profile_website');
				$this->user_profile_model->update(array('user_id' => $user_id), $profile);

				$this->data['message'] = 'Update success';
			}

			$this->data['user_info'] = $this->user_model->find_all(array('users.id' => $user_id), null, 1)->row();;
			$this->data['user_profile'] = $this->user_profile_model->find(array('user_id' => $user_id))->row();
			$this->data['roles'] = $this->role_model->get_all()->result();

			$this->template->title('SiteName', 'Người dùng', 'Chỉnh sửa');
			$this->template->build('backend/user/update', $this->data);
		}
		else
		{
			show_404();
		}
	}

	/**
	 * Ban user by ID
	 * @param int $user_id
	 */
	public function delete($user_id = NULL)
	{
		if($this->input->is_ajax_request())
		{
			if($user_ids = $this->input->post('items'))
			{
				foreach ((array)$user_ids as $user_id)
				{
					$this->user_model->check_ban($user_id)->num_rows() > 0
					? $this->user_model->unban_user($user_id)
					: $this->user_model->ban_user($user_id);
					//$this->user_model->update(array('id' => $user_id), array('banned' => 1));
				}
			}

			$data['message'] = 'OK';
			die(json_encode($data));
		}
	}

	public function process()
	{

	}

	public function check_email($email)
	{
		$result = $this->auth->is_email_available($email);
		if ( ! $result)
		{
			$this->form_validation->set_message('check_email', '%s already exist. Please choose another.');
		}

		return $result;
	}
}